import emitter from '@/plugins/mitt'
import { find, remove } from 'lodash'
import { defineStore } from 'pinia'
export const useChatStore = defineStore<'chat', any, any>('chat', {
  state: () => ({
    messages: [],
    historyMessage: [],
  }),
  actions: {
    updateHistoryMessage(data: any) {
      this.messages.unshift(...data)
      this.historyMessage.push(...data)
      // emitter.emit('scrollBottom')
    },
    // 更新消息列表
    updateMessages(data: any) {
      this.messages.push(data)
      emitter.emit('scrollBottom')
    },
    updateQueueMessages(data) {
      const queueMessage = find(this.messages, {
        type: 'queue',
      })
      if (queueMessage) {
        remove(this.messages, { type: 'queue' })
        this.messages.push(data)
      } else {
        this.messages.push(data)
      }
      emitter.emit('scrollBottom')
    },
    updateLeaveMessages(data) {
      const leaveMessage = find(this.messages, {
        type: 'leave',
      })
      if (leaveMessage) {
        remove(this.messages, { type: 'leave' })
        this.messages.push(data)
      } else {
        this.messages.push(data)
      }
      emitter.emit('scrollBottom')
    },
    removeQueueMessages() {
      remove(this.messages, { type: 'queue' })
      emitter.emit('scrollBottom')
    },
  },
  getters: {
    // 消息列表
    messageList: (state) => state.messages,
  },
  persist: {
    key: 'chat', //存储名称
    storage: localStorage, // 存储方式
    serializer: {
      serialize: (value) => JSON.stringify(value),
      deserialize: (value) => JSON.parse(value),
    },
    beforeHydrate: () => {}, // 从 storage 恢复数据之前触发
    afterHydrate: () => {}, // 从 storage 恢复数据之后触发
    omit: ['messages'], // 默认不持久化
    pick: [], // 默认持久化
  },
})
